<template>
  <view @click="isMore = false">
	  <view class="home-box" @tap="toHome()">
	  	<!-- 首页 -->
		<img :src="OSS_HOST +'img/btn-home.png'" alt="">
		
	  </view>
    <view class="goods-head" :style="'background:rgba(255,255,255,' + PageScrollTop / 100 + ')'">
      <!-- 返回 -->
      <view class="back" @click="onBack">
        <view class="back-one" :class="{ action: PageScrollTop > 120 }">
          <text></text>
        </view>
      </view>
      <!-- tab切换 -->
      <view class="head-tab" v-if="PageScrollTop > 120">
        <view class="tab" :class="{'action':TabShow===0}" @click="onTab(0)">
          <text>商品</text>
          <text class="line"></text>
        </view>
        <view class="tab" :class="{'action':TabShow===1}" @click="onTab(1)">
          <text>评价</text>
          <text class="line"></text>
        </view>
        <view class="tab" :class="{'action':TabShow===2}" @click="onTab(2)">
          <text>详情</text>
          <text class="line"></text>
        </view>
      </view>
      <!-- 分享更多 -->
      <view class="share-more">
        <view class="share-more-one" :class="{ action: PageScrollTop > 120 }">
       <!--   <view class="list">
            <text class="iconfont icon-share"></text>
          </view>
          <view class="list" @click.stop="isMore = !isMore">
            <text class="iconfont icon-diandian"></text>
          </view> -->
        </view>
        <view class="mroe-list" v-show="isMore">
          <navigator class="list">
            <view class="icon">
              <text class="iconfont icon-xiaoxi"></text>
            </view>
            <view class="title">
              <text>消息</text>
            </view>
          </navigator>
          <navigator open-type="switchTab" url="/pages/home/home" class="list">
            <view class="icon">
              <text class="iconfont icon-home"></text>
            </view>
            <view class="title">
              <text>首页</text>
            </view>
          </navigator>
          <navigator class="list">
            <view class="icon">
              <text class="iconfont icon-guanzhu"></text>
            </view>
            <view class="title">
              <text>我的关注</text>
            </view>
          </navigator>
          <navigator class="list">
            <view class="icon">
              <text class="iconfont icon-zuji"></text>
            </view>
            <view class="title">
              <text>浏览记录</text>
            </view>
          </navigator>
        </view>
      </view>
    </view>
    <!-- banner，标题 -->
    <view class="banner-title">
      <!-- banner -->
      <view class="banner">
        <swiper class="screen-swiper round-dot" indicator-dots="true" circular="true" :autoplay="autoplay" interval="5000"
                duration="500">
          <swiper-item class="swiper-item" v-for="(item, index) in swiperList" :key="index">
            <image :src="item.src" mode="aspectFit " v-if="item.type == 'img'"></image>
            <video :src="item.src" controls='true' @play='play' @pause='pause'	 	enable-play-gesture="true"  autoplay  v-if="item.type == 'video'"></video>
          </swiper-item>
        </swiper>
		<view class='zhezhao' v-if="data.detail.is_otc == 2">
			<image :src="OSS_HOST+'img/drug_zhezhao.png'" mode="aspectFill" ></image>
		</view>
      </view>
      <!-- 价格 -->
      <view class="price-info" v-show="type==0">
        <view class="price">
          <text class="min">活动价￥</text>
          <text class="max">{{data.detail.price}}</text>
          <!-- <text class="min">.00</text> -->
		 <!-- <text class="cost">
		  		  ￥{{data.detail.cost}}
		  </text> -->
        </view>
		
        <view class="info">
        <!-- <view class="list" @click="onShareType">
            <text class="iconfont" style="font-size: 48rpx;">&#xe630;</text>
            <text>分享</text>
          </view> -->
          <!-- <view class="list" @click="onAttention"> -->
				<!-- plain="true" 去掉边框 -->
			  	 <!-- <Button open-type='share'  style="border-style:none;" plain="true"><text class="iconfont" style="font-size: 48rpx;">&#xe630;</text></Button> -->
				<!-- <text class="iconfont" :class="AttentionShow===0?'icon-guanzhu-off':'icon-guanzhu-on action'"></text> -->
				<!-- <text>分享</text> -->
          <!-- </view> -->
        </view>
      </view>
	  
			<!-- 限时抢购 -->
			<!-- <view class="flash-price" v-show="type==1">
				<view class="price-item">
					<view class="icon-item">
						<text class="iconfont icon-flash-sale"></text>
					</view>
					<view class="price">
						<view class="current-price">
							<text class="min">￥</text>
							<text class="max">99</text>
							<text class="min">.00</text>
						</view>
						<view class="original-price">
							<text>￥149.00</text>
						</view>
					</view>
					<view class="tag">
						<text class="iconfont icon-flash-naozhong"></text>
					</view>
				</view>
				<view class="time-item">
					<view class="title">
						<text>距结束还剩：</text>
					</view>
					<view class="time">
						<text class="num">02</text>
						<text class="dot">:</text>
						<text class="num">46</text>
						<text class="dot">:</text>
						<text class="num">52</text>
					</view>
				</view>
			</view> -->
      <!-- 标题 -->
      <view class="goods-title">
        <text>{{data.detail.name}}</text>
      </view>
      <!-- 开通会员 -->
      <!-- <view class="dredge-vip">
        <view class="title">
          <text class="iconfont icon-vip"></text>
          <text>
            开通年卡会员预计估算优惠
            <text class="col">15.37</text>
            元
          </text>
        </view>
        <view class="dredge">
          <text>立即</text>
          <text>开通</text>
        </view>
      </view> -->
    </view>
    <!-- 优惠积分 -->
    <view class="goods-discounts">
     <!-- <view class="list">
        <view class="title">积分</view>
        <view class="content">
          <text>购买本商品可获得100积分</text>
        </view>
        <view class="more">
          <text class="iconfont icon-more"></text>
        </view>
      </view> -->
      <view class="list" @click="$refs['GoodsServe'].show()">
        <view class="title">服务</view>
        <view class="content">
          <view class="serve">
            <!-- <text class="iconfont icon-baozheng"></text> -->
            <text>退款保证,</text>
          </view>
          <view class="serve">
            <!-- <text class="iconfont icon-baozheng"></text> -->
            <text>物流配送</text>
          </view>
        </view>
        <view class="more">
          <text class="iconfont ">&#xe620;</text>
        </view>
      </view>
      <!-- <view class="list" @click="$refs['GoodsCoupon'].show()">
        <view class="title">领券</view>
        <view class="content">
          <view class="coupon-list">
            <view>满19减5</view>
          </view>
          <view class="coupon-list">
            <view>满19减5</view>
          </view>
        </view>
        <view class="more">
          <text class="iconfont icon-more"></text>
        </view>
      </view> -->
    </view>
    <!-- 属性规格  $refs['GoodsAttr'].show(1)-->
    <view class="goods-discounts">
      <view class="list" @click="submit(buyType)">
        <view class="title">已选</view>
        <view class="content">
          <text>{{message.replaceAll('^','.')}},x{{num}}</text>
        </view>
        <view class="more">
          <text class="iconfont ">&#xe620;</text>
        </view>
      </view>
	  <view class="list"  v-if="data.detail.demandId !=''">
	    <view class="title">可支付</view>
	    <view class="content" >
			 <view class='time font-color' >
			  
			   <text>{{countDownHour}}</text> 时
			   <text>{{countDownMinute}}</text> 分
			   <text>{{countDownSecond}}</text> 秒
			 </view>
	    </view>
	    <view class="more">
	      <text class="iconfont ">&#xe620;</text>
	    </view>
	  </view>
	 <view class="normsValue">
		  
		  <view v-for="item in data.normsValue" class="norms-box">
			  <view>{{item.nroms_name.replaceAll('^','.')||'默认'}}</view>
			  <view>{{item.batch_price}}元</view>
		  </view>
	  </view>
	
      <!-- <view class="list">
        <view class="title">送至</view>
        <view class="content">
          <view class="serve">
            <text class="iconfont icon-dingwei"></text>
            <text>黑龙江哈尔滨道外</text>
          </view>
        </view>
        <view class="more">
          <text class="iconfont icon-more"></text>
        </view>
      </view> -->
     <view class="list">
        <view class="title">运费</view>
        <view class="content">
          <text>{{noDeliveFee}} </text>
        </view>
        <view class="more"></view>
      </view>
	  <view class="list">
		  <view class="title">业务员</view>
		  <view class="content">
		    <text>{{kefu_tel}} </text>
		  </view>
		  <view class="more"></view>
	  </view>
    </view>
    <!-- 评价 -->
    <view class="evaluate-data" ref="evaluate">
     <!-- <view class="title-more" @click="onEvaluate">
        <view class="title">
          <text>评价</text>
          <text class="num">999+</text>
        </view>
        <view class="more">
          <text class="iconfont icon-more"></text>
        </view>
      </view>
      <view class="evaluate-list">
        <view class="user-info">
          <view class="thumb">
            <image src="/static/img/user_pic.jpg" mode=""></image>
          </view>
          <view class="nickname-grade">
            <view class="nickname">
              <text>爱笑的汤姆</text>
            </view>
            <view class="grade">
              <text class="cuIcon-favorfill lg text-gray"></text>
            </view>
          </view>
        </view>
        <view class="content">
          <view class="character">
            <text class="two-omit">搭建啊激动了阿建档立卡点击就阿卡丽登记卡加端口几啊开了都金坷垃就恐龙当家哦架空</text>
          </view>
          <view class="attr">
            <text>蓝色</text>
          </view>
          <view class="thumb-list">
            <view class="list">
              <image src="/static/img/goods_banner_01.webp" mode=""></image>
            </view>
            <view class="list">
              <image src="/static/img/goods_banner_02.webp" mode=""></image>
            </view>
            <view class="list">
              <image src="/static/img/goods_banner_03.webp" mode=""></image>
            </view>
          </view>
        </view>
        <view class="look-all" @click="onEvaluate">
          <text>查看全部评价</text>
        </view>
      </view> -->
    </view>
    <!-- 排行榜 -->
   <!-- <view class="ranking-list">
      <view class="ranking-title">
        <view class="title">排行榜</view>
      </view>
      <view class="goods-list">
        <view class="list" v-for="(item, index) in data.product" :key="index" @tap="todetail(item.id)">
          <view class="thumb">
            <image :src="item.cover_image"></image>
          </view>
          <view class="title">
            <text class="two-omit">{{item.name}}</text>
          </view>
          <view class="price">
            <text>￥{{item.price}}</text>
          </view>
        </view>
      </view>
    </view> -->
	
    <!-- 商品介绍 -->
    <view class="products-introduction product-detail" ref="products">
      <view class="title">
        <text>商品介绍</text>
      </view>
	 <view class="text">
	  	<rich-text type="text mod" decode="true" :nodes="data.detail.description" style="line-height: 25px;">
	  		
	  	</rich-text>
	  
	  	
	  </view>
      <!-- <view class="content" v-html="web_content"></view> -->
    </view>
	
    <!-- 底部 -->
    <view class="page-footer">
      <view class="footer-fn">
        <view class="list" >
			
			<button  plain="true"  open-type="contact"  style="  border-style:none; line-height: 40rpx;   padding: 0;  display: block;font-size: 28rpx;">
			   <view class="">
					<text class="iconfont ">&#xe619;</text>
			   </view>	
			   <text>联系客服</text>
		   </button>
        </view>
        <!-- <view class="list" @click="onToCart">
          <text class="iconfont ">&#xe61f;</text>
          <text>购物车</text>
        </view> -->
      </view>
      <view class="footer-buy">
        <view class="cart-add" @tap="submit('addCard')" > 
          <text>加入购物车</text>
        </view>
        <view class="buy-at" @tap="submit('buy')">
          <text>立即购买</text>
        </view>
      </view>
	  
    </view>
	
	
	<uni-popup ref="checkShare" type="bottom" custom="true" >
		<view class="share-box">
			<view class="wx-share share-item">
				 <Button open-type='share'  style="border-style:none;" plain="true"><text class="iconfont" style="font-size: 96rpx;">&#xe636;</text></Button>
				 <text>微信分享</text>
			</view>
			<view class="haibao share-item" @tap="onShareHaibao">
				<view class="item-icon">
					<text class="iconfont" style="font-size: 96rpx;">&#xe637;</text>
				</view>	
				<text>分享海报</text>
			</view>
		</view>
	</uni-popup>
	<uni-popup ref="vipCard" type="center" custom="true" >
		<view class="vipCard-box" @tap.stop="toVipCard()">
			<view class="img">
				<image :src="OSS_HOST+'img/vip_open.png'" width="550rpx"  ></image>
			</view>
			<view class="close">
				<text class="iconfont" @tap.stop="$refs['vipCard'].close()" >&#xe621;</text>
			</view>
		</view>
	</uni-popup>
	<!-- 选规格方式 -->
	<uni-popup ref="checkVenue" type="bottom" custom="true" >
		
		<view class="select-box">
			<view class="close" @tap="$refs['checkVenue'].close()" ><img src="http://api.xingdongty.com/uploader/upload/202207/13/2022071310570162ce347db2881.png" alt="" ></view>
			<view class="content">
				<view class="goods-box">
					<view class="img-item">
						<image :src="norms_cover_image" mode="aspectFit"></image>
					</view>
					<view class="price-item">
						<view class="price"><text>￥</text>  {{price}}</view>
						<!-- <view class='cost'>￥{{cost}}</view> -->
					</view>
				</view>
				<!-- <view class="title">
					{{data.detail.name}}
				</view>	
				<view class="price">
					￥{{price}}
				</view>	 -->
				<view class="time">
					库存：{{number}}
				</view>	
				<view class="name">
					{{message.replaceAll('^','.')}}
				</view>	
				<view class="norms" >
					<tui-list-cell :hover="false" unlined="all" class="tui-list ">
				
						<view class="other-type-box">
							<view class="row" v-for="item, key in list.result" :class="{hl: highKeys[key]}">
								<view class="name">
				
									{{key}}
								</view>
								<view class="mod-box">
									<view class="mod" v-for="value in item"
										@click="handleActive(key, value)"
										v-bind:class="{'yes-mod theme-boder': value.active, 'cc': !value.active && value.disabled}">
										<view class="text">
											{{ value.name.replaceAll('^','.') }}
										</view>
									</view>
				
								</view>
							</view>
						</view>
				
					</tui-list-cell>
				</view>
				<view class="norms-number" >
					<view class="tit">数量</view>
					<view class="number">
						<text class="iconfont " @tap="setNum('jian')">&#xe61b; </text>
						<input type="number" v-model="num" maxlength="8" @blur="changeNum"  >
						<text class="iconfont " @tap="setNum('jia')">&#xe61c;</text>
					</view>
				</view>
			
				<view class="btn" @tap="topayDetail()">
					<view class="btn-submit">
						确认
					</view>	
				</view>	
			</view>	
			
		</view>
		
	</uni-popup>
	<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />
    <!-- 服务弹窗 -->
    <goods-serve ref="GoodsServe"></goods-serve>
    <!-- 优惠券 -->
    <goods-coupon ref="GoodsCoupon"></goods-coupon>
    <!-- 属性规格 -->
    <goods-attr ref="GoodsAttr"></goods-attr>
	
	
	
  </view>
</template>

<script>
import { mapGetters } from 'vuex';
import GoodsServe from '@/components/GoodsServe/GoodsServe.vue';
import GoodsCoupon from '@/components/GoodsCoupon/GoodsCoupon.vue';
import GoodsAttr from '@/components/GoodsAttr/GoodsAttr.vue';
import uniPopup from '@/components/uni-popup/uni-popup.vue'
import store from '@/store/index.js';
import cart from '@/utils/cartshop.js' ;
import {oss_host} from '@/config/config.js';
// import uParse from '@/components/uni/uParse/src/wxParse'
export default {
  components: {
    GoodsServe,
    GoodsCoupon,
    GoodsAttr,
	uniPopup,
	// uParse
  },
  data() {
    return {
      TabShow: 0,
      isMore: false,
      AttentionShow: 0,
	 OSS_HOST: oss_host,
	 // 倒计时
	 countDownHour: '00',
	 countDownMinute: '00',
	 countDownSecond: '00',
	 autoplay:true,//自动播放
	 kefu_tel:'1',
	 
      swiperList: [
        
       
      ],
	 
        web_content:
          '<div class="m-img"><img src="https://zhedplus.oss-cn-hangzhou.aliyuncs.com/content_img/20191118/1fb5ff162f25fd4c7383bd998ff2fde9.jpg"><div class="tools" hidden><i class="fa fa-arrow-up move-up"></i><i class="fa fa-arrow-down move-down"></i><em class="move-remove" hidden ><i class="fa fa-times" aria-hidden="true"></i> 移除</em><div class="cover"></div></div></div>',
		PageScrollTop: 0,
		type: 0,
		id:'',
		
		product_norms_value_id:'',		
		checkIndex:0,
		price:0,
		norms_value_id: "", //normsValue规格的id  不是sku的id
		norms_value_name:'',
		normsName: "norms_value_id",
		// 属性名称信息
		keys: [],		
		// 数据集合{list.result list.items}
		list: {},
		// 分隔符
		spliter: '\u2299',
		result: {},
		message: "",
		highKeys: {},
		// 其他属性储存数组
		sel: [],
		sku: [],
		norms_cover_image:'',
		cost:'',
		vipStatus:false,
		
		
		num:1,//购买数量
		number:0,//规格动态库存
		cover_image:'',//规格图
		buyType:'buy',
		data:{
			detail:[],
			normsValue:[],
			normsList:[],
			product:[],
			userInfo:{},
		},
		noDeliveFee:100,
		code:'',//条码
		cartList:{},
    };
  },
	computed: {
		
		//注册网络状态
		...mapGetters(['netWorkType', 'loginStatus'])
	},
	
	onLoad(e) {
		// console.log(e)
		if(typeof e.type !='undefined'){
			this.type = e.type||0;
		}
		if(typeof e.id !='undefined'){
			this.id =e.id||0;
		}
		if(typeof e.code !='undefined'){
			this.code = e.code||''; //条码
		}
		
		
		if(typeof e.user_id !='undefined'){
			// 分享 非链接类型
			uni.setStorageSync('inviteUserId', e.user_id);
		}
		if(typeof e.q!= "undefined"){
			// 扫码进入
			let scene = decodeURIComponent(e.q)
			// store.dispatch('setPromotionId', this.getQueryVariable('promotion_id', scene))
			let inviteUserId = this.$service.getQueryVariable('user_id', scene)			
			// 邀请人id
			uni.setStorageSync('inviteUserId', inviteUserId);
			let id = this.$service.getQueryVariable('id', scene)
			this.id  = id
			// that.adv_channel = adv_channel
		}
		this.getDetail()
		this.cartList = uni.getStorageSync('batchCartList')==''?{}:JSON.parse(uni.getStorageSync('batchCartList'))
		// this.cartList = uni.getStorageSync('cartList')==''?{}:JSON.parse(uni.getStorageSync('cartList'))
		// let goods2 = {product_id:2,norms_value_id:2,store_id:2,store_name:'测试2号门店',product_name:'葡萄',norms_name:'5斤装',price:20,number:1,src:'/static/img/goods_thumb_09.png'}
		//   cart.add(goods2,this.cartList,(res)=>{
		//      console.log(res)
		//      uni.setStorageSync('cartList',JSON.stringify(res.data.cartList))
		//    });
		  
		  
		  
		  // let goods = {norms_value_id:goodsKey,store_id:storeKey}
		  
		  // cart.desc(goods,_this.payCartList,(res)=>{
		  //         uni.setStorageSync('payCartList',JSON.stringify(res.data.cartList))
		  //         _this.payCartList = res.data.cartList
		  //     });
	},
	onPageScroll(e) {
		
		this.PageScrollTop = e.scrollTop;
	},
	reload(){
		let page = getCurrentPages().pop();
		if (page == undefined || page == null) return;
		page.curSegment = 0;
		page.onShow();
	},
	//2.分享到朋友圈
	// onShareTimeline(res) {
	// 	const _this = this;
		
	// 	const shareTitle = 'OPPORT瓯品医械商城'
	// 	const shareText =_this.data.detail.name
	// 	// console.log('888',`/pages/GoodsDetails/GoodsDetails?id=${_this.id}&user_id=${_this.data.userInfo.id}`)
	//     return {
	//         title: shareTitle,
	//         path: `/pages/GoodsDetails/GoodsDetails?id=${_this.id}&user_id=${_this.data.userInfo.id}`,
	//         query:`id=${_this.id}&user_id=${_this.data.userInfo.id}`,
	// 		imageUrl:  _this.data.detail.cover_image,
	//     }
	// },
	// onShareAppMessage: function () {
	//      const _this = this;
	     
	//      const shareTitle = 'OPPORT瓯品医械商城'
	// 	 const shareText =_this.data.detail.name
	//      return {
	//         title: _this.data.detail.name,//标题
	//         desc: _this.data.detail.name,
	//         path: `/pages/GoodsDetails/GoodsDetails?id=${_this.id}&user_id=${_this.data.userInfo.id}`, // 路径，传递参数到指定页面。
	// 		imageUrl: _this.data.detail.cover_image,
			
	// 	 }
	//    },
  methods: {
	  // kefu(){
		 //  console.log(11212121)
		 //  uni.openCustomerServiceChat({
		 //    extInfo: {url: 'https://work.weixin.qq.com/kfid/kfcb95a7443eb2908b1'},
		 //    corpId: 'ww7f22b799339e78c3',
		 //    success(res) {
			// 	console.log(res)
			// },
			// fail(res){
			// 	console.log(111111,res)
			// }
		 //  })
	  // },
	  submit(type){
		  let _this =this
		  this.buyType = type
	  	this.initData()
		if(!this.loginStatus){
			_this.$refer.setVilit('')
			this.$refs.popupvLogin.open()
			
			
			return ;
		}
		// this.getDetail()
		
		if(!this.vipStatus){
			
			this.$refs.vipCard.open();
		}else{
			this.$refs.checkVenue.open()
		}
	  },
    /**
     * 返回
     */
    onBack() {
		
      uni.navigateBack({
		  success: (res) => {
				//  返回页面 重新加载 onLoad()
		  			let page = getCurrentPages().pop();
		  			if (page == undefined || page == null) return;
		  			page.curSegment = 0;
		  			page.onLoad();
		  		},
	  });
    },
	// 时分秒
	time(timeStamp,that) {
	  var interval = null,totalSecond = timeStamp - Date.parse(new Date()) / 1000;
	  interval = setInterval(function () {
	    // 秒数  
	    var second = totalSecond;
	
	    // 小时位  
	    var hr = Math.floor(second / 3600);
	    var hrStr = hr.toString();
	    if (hrStr.length == 1) hrStr = '0' + hrStr;
	
	    // 分钟位  
	    var min = Math.floor((second - hr * 3600) / 60);
	    var minStr = min.toString();
	    if (minStr.length == 1) minStr = '0' + minStr;
	
	    // 秒位  
	    var sec = second - hr * 3600 - min * 60;
	    var secStr = sec.toString();
	    if (secStr.length == 1) secStr = '0' + secStr;
	   
	      this.countDownHour= hrStr,
	      this.countDownMinute= minStr,
	      this.countDownSecond= secStr,
	    
	    totalSecond--;
	    if (totalSecond <= 0) {
	      clearInterval(interval);
		   this.data.detail.demandId =''
	      // uni.showToast({
	      //   title: '活动已结束',
	      //   icon: 'none',
	      //   duration: 1000,
	      //   mask: true,
	      // })
	     
						this.countDownHour= '00'
	      this.countDownMinute= '00'
	      this.countDownSecond= '00'
	      
	    }
	  }.bind(this), 1000);
	  this.interval=interval;
	},
	toHome(){
		let _this= this
		uni.switchTab({
			url:'/pages/home/home',
			success: (res) => {
						let page = getCurrentPages().pop();
						if (page == undefined || page == null) return;
						page.curSegment = 0;
						page.onLoad();
					},
		})
	},
    /**
     * tab
     */
    onTab(type) {
      this.TabShow = type;
      switch (type) {
        case 0:
          uni.pageScrollTo({
          	scrollTop: 0,
          	duration: 300
          });
          break;
        case 1:
          uni.createSelectorQuery().select(".evaluate-data").boundingClientRect((data) => { //data - 各种参数
            uni.pageScrollTo({
							scrollTop: this.PageScrollTop + data.top -50,
							duration: 300
						});
          }).exec()
          break;
        case 2:
          uni.createSelectorQuery().select(".products-introduction").boundingClientRect((data) => { //data - 各种参数
            uni.pageScrollTo({
            	scrollTop: this.PageScrollTop + data.top - 50,
            	duration: 300
            });
          }).exec()
          break;
      }
    },
	todetail(id){
		let _this =this
		_this.$refer.setVilit('/packageBatch/pages/GoodsDetails/GoodsDetails')
		let callback = function(url) {
			// _this.$refs.popupvLogin.open()
		}
		let data = {
			id:id,
		}
		_this.$refer.toUrl(callback, data)
		// break;
		
	},
	toVipCard(){
		let _this =this
		_this.$refer.setVilit('/packageBatch/pages/my/card/index')
		let callback = function(url) {
			_this.$refs.popupvLogin.open()
		}
		let data = {
			// id:id,
		}
		_this.$refer.toUrl(callback, data)
	},
	play(){
		this.autoplay=false
	},
	pause(){
		this.autoplay=true
	},
	getDetail(){
		const _this = this
		// console.log(1111111)
		// console.log(_this.id,_this.code)
		var opt = {
			url: '/product/detail', 
			data:{
				id:_this.id||'',
				shape_code:_this.code||''
				
			},
			success: function(res) { 
			 
				if (res.status == 1) { 
					 let result = res.data
					_this.swiperList = result.detail.album_image
					_this.kefu_tel = result.kefuTel||''
					// 测试
					// _this.swiperList[3] ={
					// 	org: "https://app.yaopingsshop.com/uploader/upload/202301/16/2023011616210763c508f308ca8.png",
					// 	path: "2023011616210763c508f308ca8.png",
					// 	src: "http://api.yaopingsshop.com/uploader/upload/202305/10/20230510111345645b0be923192.mp4",
					// 	type: "video",
					// }
					_this.data.detail =result.detail
					_this.data.normsValue = res.data.normsValue
					_this.data.normsList = res.data.normsList
					_this.data.product = result.product
					_this.vipStatus = result.vipStatus
					_this.data.detail.description = _this.data.detail.description.replace(/\<img/gi,
						'<img style="max-width:100%;height:auto;display:block;margin:0 auto;" ').replace(/&nbsp;/g, '\xa0')
					if(_this.loginStatus){
						_this.getUserInfo();
					}
					_this.time(_this.data.detail.end_time,_this);
					_this.noDeliveFee = result.noDeliveFee
					
					
				}  else{
					uni.showToast({
						icon:'none',
						title:'无此产品信息'
					})
					setTimeout(function () {
						
						 _this.onBack()
						
					}, 3000);
					
					
					
				}
				// _this.skeletonShow = false;
			}
		};
				
		
		this.$service.GetApi(opt) //网络
	},
	getUserInfo(){
		let _this = this
		var opt = {
			url: '/user/userInfo',
			data: {
		
			},
			success: function(res) {
		
				if (res.status == 1) {
					_this.data.userInfo =res.data.userInfo
					
				} else {
					
				}
			}
		};
		
		_this.$service.GetApi(opt);
	},
	
	
    /**
     * 去购物车
     */
    onToCart() {
		
		if(this.loginStatus){
			// 切换
			uni.switchTab({
			  url: '/pages/cart/cart',
			  success: (res) => {
			  			let page = getCurrentPages().pop();
			  			if (page == undefined || page == null) return;
			  			page.curSegment = 0;
			  			page.onLoad();
			  		},
			})
		}else{
			
			this.$refs.popupvLogin.open()
		}
     
    },
    /**
     * 降价通知点击
     */
    onDepreciate() {
      uni.showToast({
        title: '降价通知提醒成功',
        icon: 'success'
      })
    },
	topayDetail(){
		let _this = this
		// if(!this.loginStatus){
		// 	this.$refs.popupvLogin.open()
		// 	return 
		// }
		switch(_this.buyType){
			case 'addCard':
				// if(_this.data.detail.is_otc == 2){
				// 	uni.showToast({
				// 		icon:'none',
				// 		title:'处方药暂时不能添加至购物车！'
				// 	})
				// 	return 
				// }
				//加入购物车
				// console.log('*******',this.cartList)
				let goods2 = {
					product_id:this.id,
					norms_value_id:this.product_norms_value_id,
					store_id:this.data.detail.store_id,
					store_name:this.data.detail.store_name,
					product_name:this.data.detail.name,
					norms_name:this.data.normsValue[this.norms_value_id].norms_name,
					price:this.price,
					number:this.num,
					src:this.data.detail.cover_image,
				}
				  cart.add(goods2,this.cartList,(res)=>{
				     // console.log(res)
				     uni.setStorageSync('batchCartList',JSON.stringify(res.data.cartList))
				   });
				
				this.$refs['checkVenue'].close()
				uni.showToast({
				  title: '添加成功',
				  icon: 'success'
				})
				  
			break
			case 'buy':
				
				
				//跳转支付页 
				_this.$refer.setVilit('/pages/PayOrder/submit_order')
				// if(_this.data.detail.is_otc ==2 && _this.data.detail.demandId ==''){
				// 	// 处方流程   当为处方药 并 半小时内未开方时 跳转至处方流程 ，
				// 	_this.$refer.setVilit('/packageRx/pages/index')
				// }
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				
				let product = [
					{
						id:this.id,
						norms_value_id:this.product_norms_value_id,
						num:this.num,
						store_id:this.data.detail.store_id,
						store_name:this.data.detail.store_name,
						price:this.data.detail.price,
					},
				]
				
				// 结合购物车多产品的情况
				let data = {
					product:JSON.stringify(product),
					demandId:_this.data.detail.demandId||'',
					// type:'batchCart',
					related_type:'batch',
				}
				uni.setStorageSync('param',JSON.stringify(data))
				_this.$refer.toUrl(callback, data)
			break
			default :
				uni.showToast({
				  title: '意外的错误',
				  icon: 'error'
				})
			break
			
		}
		
	},
	onShareType(){
		let _this = this
		if(!_this.loginStatus){
					 // uni.showToast({
					 // 	icon:'none',
						// title:''
					 // })
					  _this.$refs.popupvLogin.open()
					 return 
		}
		if(_this.data.userInfo.id == 'undefined'){
			_this.getUserInfo();
		}
		this.$refs.checkShare.open()
	},
	onShareHaibao(){
		
		let _this= this
		//跳转支付页
		_this.$refer.setVilit('/pages/GoodsDetails/qrcode/qrcode')
	
		let callback = function(url) {
			_this.$refs.popupvLogin.open()
		}
		
		
		// 结合购物车多产品的情况
		let data = {
			id:_this.data.detail.id,
			
		}
		// uni.setStorageSync('param',JSON.stringify(data))
		_this.$refer.toUrl(callback, data)
	},
    /**
     * 关注点击
     */
    onAttention() {
      // if (this.AttentionShow === 0) {
      //   this.AttentionShow = 1;
      //   uni.showToast({
      //     title: '关注成功',
      //     icon: 'none'
      //   })
      // } else {
      //   this.AttentionShow = 0;
      //   uni.showToast({
      //     title: '取消成功',
      //     icon: 'none'
      //   })
      // }

    },
		/**
		 * 评价点击
		 */
		onEvaluate(){
			uni.navigateTo({
				url: '/pages/GoodsEvaluateList/GoodsEvaluateList'
			})
		},
	//数量
	setNum(type){
		switch(type){
			case 'jia':
				this.num = this.num+1
				if(this.num >this.number){
					this.num = this.number
				}
			break
			case 'jian':
				this.num = this.num-1
				if(this.num<1){
					this.num =1
				}
			break
			
		}
	},
	changeNum(e){
		this.num = parseInt(this.num)
		if(!this.num){
			this.num =1
		}
		if(this.num<1){
			this.num =1
		}
		if(this.num >this.number){
			
			// this.num = this.number
			uni.showToast({
				icon:'none',
				title:'超出产品库存数量.'
			})
		}
		
		
	},
	// 多规格选择 start
	/**
	 * 初始化数据
	 * @return
	 */
	initData() {
		// this.data = JSON.parse(data);
		let isHas = false;
		let norms_value_id = 0
		for (let i = 0; i < this.data.normsList.length; i++) {
			if (norms_value_id == this.data.normsList[i][this.normsName]) {
				isHas = true;
				break
			}
		}
		this.norms_value_id = isHas ? norms_value_id : this.data.normsList[0][this.normsName];
		// console.log(1111)
		// console.log(this.norms_value_id)
		this.result = {};
		this.keys = this.getAllKeys();
		// console.log('key****',this.keys)
		for (let i = 0; i < this.keys.length; i++) {
			this.highKeys[this.keys[i]] = false;
		}
	
		this.list = this.combineAttr(this.data.normsList, this.keys);
		// console.log('list****',this.list)
		//console.log(this.list.items)
		this.initSeleted(this.norms_value_id);
		this.buildResult(this.list.items)
		this.updateStatus(this.getSelectedItem());
		this.showResult();
	},
	/**
	 * 正常属性点击
	 */
	handleNormalClick(key, value) {
		for (let i in this.list.result[key]) {
			if (i != value.name) {
				this.list.result[key][i].active = false;
			} else {
				this.list.result[key][i].active = true;
			}
		}
	},
	
	/**
	 * 无效属性点击
	 */
	handleDisableClick(key, value) {
		this.list.result[key][value.name]["disabled"] = false;
		// 清空高亮行的已选属性状态（因为更新的时候默认会跳过已选状态）
		for (let i in this.list.result) {
			if (i != key) {
				for (let x in this.list.result[i]) {
					this.list.result[i][x].active = false;
				}
			}
		}
	
		this.updateStatus(this.getSelectedItem());
	},
	
	/**
	 * 高亮行
	 */
	highAttributes: function() {
		for (let key in this.list.result) {
			this.highKeys[key] = true;
			for (let attr in this.list.result[key]) {
				if (this.list.result[key][attr].active === true) {
					this.highKeys[key] = false;
					break;
				}
			}
		}
	},
	
	/**
	 * 点击事件处理
	 * @param  key   点击的行
	 * @param  value 点击的按钮的数据
	 */
	handleActive: function(key, value) {
		this.sel[key] = value //让数组sel的第topkey+1的元素的值等于subkey
		// console.log(1111)
		// console.log(this.sel)
		if (value.active == true) {
			return false;
		}
	
		this.handleNormalClick(key, value);
		if (value.disabled === true) {
			this.handleDisableClick(key, value);
		}
	
		this.updateStatus(this.getSelectedItem());
	
		this.highAttributes();
		this.showResult();
	},
	/**
	 * 计算属性
	 * @param  {[type]} data [description]
	 * @param  {[type]} keys [description]
	 * @return {[type]}      [description]
	 */
	combineAttr(data, keys) {
		let allKeys = []
		let result = {}
	
		for (let i = 0; i < data.length; i++) {
			let item = data[i]
			let values = []
	
			for (let j = 0; j < keys.length; j++) {
				let key = keys[j]
				if (!result[key]) {
					result[key] = {};
				}
	
				if (!result[key][item[key]]) {
					result[key][item[key]] = {
						"name": item[key],
						"active": false,
						"disabled": true
					};
				}
	
				values.push(item[key]);
			}
	
			allKeys.push({
				path: values.join(this.spliter),
				sku: item['norms_value_id']
			});
		}
	
		return {
			result: result,
			items: allKeys
		}
	},
	/**
	 * 获取所有属性
	 * @return {[type]} [description]
	 */
	getAllKeys() {
		let arrKeys = [];
		// console.log(11111);
		//console.log(this.normsList);
		for (let attribute in this.data.normsList[0]) {
			if (!this.data.normsList[0].hasOwnProperty(attribute)) {
	
				continue;
			}
	
			if (attribute !== this.normsName) {
				arrKeys.push(attribute);
			}
		}
		// console.log(this.normsList[0])
		console.log(222,arrKeys)
		return arrKeys;
	},
	
	getAttruites(arr) {
		let result = []
		for (let i = 0; i < arr.length; i++) {
			result.push(arr[i].path)
		}
	
		return result
	},
	
	/**
	 * 生成所有子集是否可选、库存状态 map
	 */
	buildResult(items) {
		let allKeys = this.getAttruites(items)
	
		for (let i = 0; i < allKeys.length; i++) {
			let curr = allKeys[i];
			let sku = items[i].sku;
			let values = curr.split(this.spliter);
			let allSets = this.powerset(values);
	
			// 每个组合的子集
			for (let j = 0; j < allSets.length; j++) {
				let set = allSets[j]
				let key = set.join(this.spliter)
	
				if (this.result[key]) {
					this.result[key].skus.push(sku)
				} else {
					this.result[key] = {
						skus: [sku]
					}
				}
			}
		}
	},
	
	/**
	 * 获取选中的信息
	 * @return Array
	 */
	getSelectedItem() {
		let result = [];
		for (let attr in this.list.result) {
			let attributeName = '';
			for (let attribute in this.list.result[attr]) {
				if (this.list.result[attr][attribute].active === true) {
					attributeName = attribute;
				}
			}
	
			result.push(attributeName);
		}
		// console.log(2222)
		// consle.log(result)
		return result
	},
	
	/**
	 * 更新所有属性状态
	 */
	updateStatus(selected) {
		for (let i = 0; i < this.keys.length; i++) {
			let key = this.keys[i],
				data = this.list.result[key],
				hasActive = !!selected[i],
				copy = selected.slice();
	
			for (let j in data) {
				let item = data[j]["name"];
				if (selected[i] == item) {
					continue
				}
	
				copy[i] = item
				let curr = this.trimSpliter(copy.join(this.spliter), this.spliter);
				this.list.result[key][j]["disabled"] = this.result[curr] ? false : true;
			}
		}
	},
	
	trimSpliter(str, spliter) {
		// ⊙abc⊙ => abc
		// ⊙a⊙⊙b⊙c⊙ => a⊙b⊙c
		let reLeft = new RegExp('^' + spliter + '+', 'g');
		let reRight = new RegExp(spliter + '+$', 'g');
		let reSpliter = new RegExp(spliter + '+', 'g');
		return str.replace(reLeft, '')
			.replace(reRight, '')
			.replace(reSpliter, spliter)
	},
	/**
	 * 初始化选中
	 * @param  mixed|Int|String norms_value_id 需要选中的norms_value_id
	 * @return {[type]}       [description]
	 */
	initSeleted(norms_value_id) {
		for (let i in this.data.normsList) {
			if (this.data.normsList[i][this.normsName] == norms_value_id) {
				for (let x in this.data.normsList[i]) {
					if (x !== this.normsName) {
						this.list.result[x][this.data.normsList[i][x]].active = true;
					}
				}
				break;
			}
		}
	},
	/**
	 * 显示选中的信息
	 * @return
	 */
	showResult() {
		let result = this.getSelectedItem()
		// console.log(11111)
		// console.log(result)
		let s = []
		for (let i = 0; i < result.length; i++) {
			let item = result[i];
			if (!!item) {
				s.push(item)
			}
		}
	
		if (s.length == this.keys.length) {
			let curr = this.result[s.join(this.spliter)]
			if (curr) {
				// s = s.concat(curr.skus)
				this.norms_value_id = curr.skus[0];
			}
	
			this.message = s.join('\u3000');
		}
		if (this.norms_value_id != '') {
	
			this.price = this.data.normsValue[this.norms_value_id].batch_price;
			this.norms_value_name = this.message
			this.product_norms_value_id=this.data.normsValue[this.norms_value_id].norms_id
			// this.cover_image = this.data.normsValue[this.norms_value_id].cover_image
			this.number = this.data.normsValue[this.norms_value_id].number
			this.norms_cover_image = this.data.normsValue[this.norms_value_id].cover_image
			this.cost =  this.data.normsValue[this.norms_value_id].cost
		}
	
	
	
	
		// console.log(this.norms_value_id)
		// console.log(this.message)
	},
	
	
	/**
	 * 获取输入表单中的数据进行初始化
	 * @return
	 */
	getTextareaData() {
		let data = document.getElementById('values').value;
		let norms_value_id = document.getElementById("norms_value_id").value;
	
		try {
			this.data = JSON.parse(data);
			let isHas = false;
			for (let i = 0; i < this.data.length; i++) {
				if (norms_value_id == this.data[i][this.normsName]) {
					isHas = true;
					break
				}
			}
	
			this.norms_value_id = isHas ? norms_value_id : this.data[0][this.normsName];
			this.initData();
		} catch (e) {
			this.data = [];
		}
	},
	powerset(arr) {
		let ps = [
			[]
		];
		for (let i = 0; i < arr.length; i++) {
			for (let j = 0, len = ps.length; j < len; j++) {
				ps.push(ps[j].concat(arr[i]));
			}
		}
	
		return ps;
	},
	// end
  }
};
</script>

<style scoped lang="scss">
@import 'GoodsDetails.scss';
</style>
